/**
 * 导出工具函数
 * 用于处理内容格式转换和导出功能
 */

// 将Markdown转换为HTML
export const markdownToHtml = (markdown: string): string => {
  let html = markdown;

  // 移除首行标题（如果存在）
  html = html.replace(/^#\s+.+\n\n?/, '');

  // 标题
  html = html.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>');
  html = html.replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>');
  html = html.replace(/^####\s+(.+)$/gm, '<h4>$1</h4>');
  html = html.replace(/^###\s+(.+)$/gm, '<h3>$1</h3>');
  html = html.replace(/^##\s+(.+)$/gm, '<h2>$1</h2>');
  html = html.replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');

  // 粗体
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  html = html.replace(/__(.+?)__/g, '<strong>$1</strong>');

  // 斜体
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
  html = html.replace(/_(.+?)_/g, '<em>$1</em>');

  // 行内代码
  html = html.replace(/`(.+?)`/g, '<code>$1</code>');

  // 链接
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');

  // 图片
  html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" />');

  // 代码块
  html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
    return `<pre><code class="language-${lang}">${code.trim()}</code></pre>`;
  });

  // 水平线
  html = html.replace(/^---$/gm, '<hr />');
  html = html.replace(/^\*\*\*$/gm, '<hr />');

  // 无序列表
  html = html.replace(/^[-*]\s+(.+)$/gm, '<li>$1</li>');
  html = html.replace(/(<li>.*<\/li>\n?)+/g, (match) => {
    return `<ul>${match}</ul>`;
  });

  // 有序列表
  html = html.replace(/^\d+\.\s+(.+)$/gm, '<li>$1</li>');

  // 引用
  html = html.replace(/^>\s+(.+)$/gm, '<blockquote>$1</blockquote>');

  // 段落（两个以上换行符）
  html = html.replace(/\n\n+/g, '</p><p>');
  html = `<p>${html}</p>`;

  // 单个换行符转br
  html = html.replace(/\n/g, '<br />');

  // 清理空段落
  html = html.replace(/<p><\/p>/g, '');
  html = html.replace(/<p>\s*<\/p>/g, '');

  return html;
};

// 将HTML转换为Markdown
export const htmlToMarkdown = (html: string): string => {
  // 使用浏览器环境下可用的简单转换方法
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;

  // 递归处理DOM节点
  const processNode = (node: Node): string => {
    if (node.nodeType === Node.TEXT_NODE) {
      return node.textContent || '';
    }

    if (node.nodeType === Node.ELEMENT_NODE) {
      const element = node as Element;
      const children = Array.from(element.childNodes).map(processNode).join('');

      switch (element.tagName.toLowerCase()) {
        case 'h1':
          return `# ${children}\n\n`;
        case 'h2':
          return `## ${children}\n\n`;
        case 'h3':
          return `### ${children}\n\n`;
        case 'h4':
          return `#### ${children}\n\n`;
        case 'h5':
          return `##### ${children}\n\n`;
        case 'h6':
          return `###### ${children}\n\n`;
        case 'p':
          return `${children}\n\n`;
        case 'strong':
        case 'b':
          return `**${children}**`;
        case 'em':
        case 'i':
          return `*${children}*`;
        case 'u':
          return `<u>${children}</u>`;
        case 'code':
          return `\`${children}\``;
        case 'pre':
          return `\`\`\`\n${children}\n\`\`\`\n\n`;
        case 'blockquote':
          return `> ${children}\n\n`;
        case 'ul':
          return `${children}\n`;
        case 'ol':
          return `${children}\n`;
        case 'li':
          const listMarker = element.closest('ol') ? '1. ' : '- ';
          return `${listMarker}${children}\n`;
        case 'a':
          const href = element.getAttribute('href') || '';
          return `[${children}](${href})`;
        case 'img':
          const src = element.getAttribute('src') || '';
          const alt = element.getAttribute('alt') || '';
          return `![${alt}](${src})`;
        case 'table':
          return `\n${children}\n`;
        case 'thead':
        case 'tbody':
          return children;
        case 'tr':
          return `${children}\n`;
        case 'th':
        case 'td':
          return `| ${children} `;
        case 'br':
          return '\n';
        case 'hr':
          return '\n---\n\n';
        case 'div':
        case 'span':
          return children;
        default:
          return children;
      }
    }

    return '';
  };

  return processNode(tempDiv).trim();
};

// 获取编辑器内容作为Markdown
export const getEditorContentAsMarkdown = (editor: any, title?: string): string => {
  if (!editor) return '';
  
  const html = editor.getHTML();
  let markdown = htmlToMarkdown(html);
  
  // 如果有标题且内容中没有标题，添加标题
  if (title && !markdown.startsWith('#')) {
    markdown = `# ${title}\n\n${markdown}`;
  }
  
  return markdown;
};